package com.xdf.ecommerce.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author chanchaw
 * @create 2025-10-18 9:35
 */
public class HeaderTokenGatewayFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取第一个是 token 的请求头，存在则通过继续向下执行
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if("imooc".equals(token)) return chain.filter(exchange);

        // 没有找到 imooc 的请求头则返回没有权限
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder(){
        return HIGHEST_PRECEDENCE + 2;
    }
}
